<template>
	<view>
		<block>
			<uni-nav-bar @clickLeft="goBack" status-bar="true" shadow="true" left-icon="back" title=" "></uni-nav-bar>
		</block>
		<view class="out-top-tab" style="position: relative;">
			<view class="icon iconfont icon-zengjiahang add-button" v-if="showEditor" @tap="addChildTopic" />
			<block v-for="(tab,index) in tabBars" :key="tab.id">
				<view class="swiper-tab-list" :class="{'active':tabIndex==index}" @tap="tabTab(index)">
					<block>
						<text style="font-size: larger;" >{{tab}}</text>
						<view class="swiper-tab-line"></view>
					</block>
				</view>
			</block>
		</view>
		<scroll-view scroll-x class="uni-swiper-tab">
			<block v-for="(belowTab,belowIndex) in belowTabBars" :key="tab.id">
				<view class="below-swiper-tab-list" :class="{'active':belowTabIndex==belowIndex}" @tap="tabBelowTab(belowIndex)">
					<view class="swiper-tab-line1" style="margin-left: 5px;">
						<text style="font-size: large; padding-left: 8px; padding-right: 8px; "> {{belowTab}}</text>
					</view>
				</view>
			</block>
		</scroll-view>
		<!--  -->
		<swiper style="padding-bottom: 500px;" class="swiper-box" :current="tabIndex" @change="swiperChanged" :style="{height:swiperhight+'px'}">
			<swiper-item v-for="(items,index2) in newsList" :key="index2">
				<scroll-view scroll-Y :style="{height:swiperhight2+'px'}" @scrolltolower="loadmore()">
					<block v-if="tabIndex==0">
						<view class="out-input" v-show="belowTabIndex==0">
							<label class="lable-radio" style="font-weight: bold; margin-left: 15px; font-size: large;">初诊
								<radio v-model="currentTopic.isFirst" class="radio" value="r1" :checked="currentTopic.isFirst" color="#007AFF"
								 style="transform:scale(0.8)" /></label>
						</view>
						<view class="uni-form-item ">
							<view class="title">就诊时间</view>
							<input class="uni-input " disabled="true" v-model="currentTopic.consultTime"  />
						</view>
						<view class="uni-form-item " v-show="belowTabIndex==0">
							<view class="title">城市</view>
							<input disabled="true" v-model="currentTopic.location" class="uni-input " />
						</view>

						<view class="uni-form-item " v-show="belowTabIndex==0">
							<view class="title">大夫</view>
							<input disabled="true" v-model="currentTopic.doctor" class="uni-input " />
						</view>


						<view class="uni-form-item " v-show="belowTabIndex==0">
							<view class="title">诊所医院</view>
							<input disabled="true" v-model="currentTopic.clinic" class="uni-input" />
						</view>


						<view class="uni-form-item " v-show="belowTabIndex==0">
							<view class="title">求诊疾病</view>
							<input disabled="true" v-model="currentTopic.diseseName" class="uni-input" />
						</view>

						<view class="uni-form-item " >
							<view class="title">诊前情况</view>
							<text class="textarea" auto-height>
								<text v-if="currentTopic.beforeCase.length>0">{{currentTopic.beforeCase}}</text>
								<text v-else style="color: #B2B2B2;">未记录</text>
							</text>
						</view>
						<view class="uni-form-item "  >
							<view class="title">诊后情况</view>
							<text class="textarea" auto-height>
								<text v-if="currentTopic.afterCase.length>0">{{currentTopic.afterCase}}</text>
								<text v-else style="color: #B2B2B2;">未记录</text>
							</text>
						</view>
						<view class="comment-list ">
							<view class="titleDegress" >好评度</view>
							<radio-group class="coomment-list-cell">
								<label style="font-size: large;" v-for="(item, index) in degressItems" :key="item.value">
									<view style="float: left; display: inline-block; font-size: large;" v-if="index === getCurrentDegress">{{item}}
										<radio :value="item" :checked="index === getCurrentDegress" color="#007AFF" style="transform:scale(0.8)" />
									</view>
								</label>
							</radio-group>
						</view>

						<view class="uni-list list-pd">
							<view class="uni-list-cell cell-pd">
								<view class="uni-uploader">
									<view class="uni-uploader-head">
										<view class="uni-uploader-title">就医凭证</view>
										<view class="uni-uploader-info">{{currentTopic.casePics.length}}/6</view>
									</view>
									<view>
										<view class="image-out">
											<block v-for="(image,index3) in currentTopic.casePics" :key="index3">
												<view>
													<image class="image-list" :src="image" :data-src="image" @tap="previewImage"></image>
												</view>
											</block>
										</view>
									</view>
								</view>
							</view>
						</view>

					</block>

					<view v-else style="padding-bottom: 100px;">
						<block v-for="(ite,indexx) in currentComments" :key="indexx">
							<view class="uni-comment-list" v-if="!idFromNewsPage||(idFromNewsPage&&indexx==0)||(idFromNewsPage&&indexx!=0&&ite._id!=commentIdFromNewsPage)"
							 v-bind:class="{myactive:idFromNewsPage&&indexx==0}" @tap="goDetail(ite)">
								<view class="uni-comment-face">
									<image :src="ite.commentator.avatar_url" mode="widthFix"></image>
								</view>
								<view class="uni-comment-body">
									<view class="uni-comment-top" style="display: flex;">
										<text>{{ite.commentator.name}}: 楼主</text>
										<view class="uni-comment-date" style="justify-content: flex-end;">
											<view style="padding-right: 15px; ">{{ite.createdAt | FormatDate('yyyy-MM-dd HH:mm:ss') }}</view>
										</view>
									</view>
									<view class="uni-comment-content">{{ite.content}}</view>
									<view class="uni-comment-date">
										<view></view>
										<view class="uni-comment-replay-btn">{{ite.replyNum}}回复</view>
									</view>
								</view>
							</view>
						</block>
						<view class="load-more">{{getBelowText}}</view>
					</view>

				</scroll-view>

			</swiper-item>

		</swiper>

		<view class="comment-out">
			<textarea style="background-color: #FFFFFF;" v-model="newComment" class="comment-text" fixed="true"
			 placeholder-style="font-size:20px;" placeholder="请输入评论" maxlength="100">
			</textarea>
			<view class="comment-send" @tap="sentComment">
				发送
			</view>
		</view>
		<view @tap="refresh" class="refresh-button icon iconfont icon-shuaxin" />
	</view>
</template>

<script>
	import uniNavBar from "@/components/uni-nav-bar/uni-nav-bar.vue"
	import config from "@/common/config.js"
	export default {
		components: {
			uniNavBar

		},
		data() {
			return {
				tabBars: ["记录", "评论"],
				tabIndex: 0,
				// recorderIndex: [0, 0],
				belowTabBars: [1],
				belowTabIndex: 0,

				newsList: ["记录内容", "评论列表"],
				swiperhight: 100,
				swiperhight2: 100,
				topicDetail: {},
				currentTopic: {},
				degressItems: ['满意', '一般', '差'],
				fromMyTopiclist: '',
				showEditor:false,
				comments: [
					[]
				],
				currentComments: [],
				newComment: '',
				topicId: '',
				loadmoreInfoes: [{
					loadmoreText: '上拉加载更多',
					isLoadingMore: false,
					currentPage: 1
				}],
				belowText: '上拉加载更多',

				//记录动态topic
				currentTopicId: '',
				commentIdFromNewsPage: ''

			}
		},
		onLoad(option) {
			uni.getSystemInfo({
				success: (res) => {
					//减去titleBar=44px, 顶部tab=100upx
					let windowHight = res.windowHeight - 44 - uni.upx2px(100);

					this.swiperhight = windowHight;
					this.swiperhight2 = windowHight - uni.upx2px(100);
				}
			});

			this.topicId = option.id;
			console.log('this.topicId===========pppp====' + option.id);
			//from=myTopiclist
			this.fromMyTopiclist = option.from;
			if(option.from=='我的记录'){
				this.showEditor = true;
			}
			//从动态页面跳转过来后，通过改变这两个数据，实现直接切换到对应的案例的评论页。
			//要从动态页，传进来topicId和currentTopicId。
			this.currentTopicId = option.currentTopicId;
			//for make the comment be top
			this.commentIdFromNewsPage = option.commentId;
			// this.getRecorderDetail(option.id);
			this.initData();
		},
		onPullDownRefresh() {
			this.initData();
		},
		computed: {
			getCurrentDegress: function() {
				// `this` 指向 vm 实例s
				return parseInt(this.currentTopic.degress);
			},
			getBelowText: function() {
				return this.loadmoreInfoes[this.belowTabIndex].loadmoreText;
			},
			idFromNewsPage: function() {
				return this.commentIdFromNewsPage && this.commentIdFromNewsPage.length > 0 && this.currentComments[0] && this.currentComments[
					0]._id == this.commentIdFromNewsPage;
			}

		},
		methods: {
			loadmore() {
				if (this.tabIndex == 0) {
					return;
				}
				var obj = this.loadmoreInfoes[this.belowTabIndex];
				// if (!this.isLoadingMore && this.loadmoreText != "没有更多数据") {
				if (!obj.isLoadingMore && obj.loadmoreText != "没有更多数据") {
					this.loadmoreInfoes[this.belowTabIndex].isLoadingMore = true;
					this.loadmoreInfoes[this.belowTabIndex].loadmoreText = "数据加载中..";
					this.getRecorderCommentList(this.belowTabIndex, obj.currentPage, true);
					console.log("loadmore----" + obj.currentPage)
				}
			},
			initData() {
				for (var i = 0; i < this.loadmoreInfoes.length; i++) {
					this.loadmoreInfoes[i].loadmoreText = '上拉加载更多';
					this.loadmoreInfoes[i].currentPage = 1;
					this.loadmoreInfoes[i].isLoadingMore = false;
				}
				this.topicDetail = {};
				this.currentTopic = {};
				this.comments = [
					[]
				];
				this.newComment = '';
				this.belowTabBars = [1];
				this.getRecorderDetail(this.topicId);
			},
			refresh() {
				uni.startPullDownRefresh({})
			},
			tabTab(index) {
				this.tabIndex = index;
				console.log('上面切换' + index);
			},
			swiperChanged(e) {
				console.log('yyyyyuuu' + e.detail);
				this.tabIndex = e.detail.current;
			},
			tabBelowTab(index) {
				this.belowTabIndex = index;
				console.log("tabBelowTab====");
				console.log(index);
				if (index > 0) {
					this.currentTopic = this.topicDetail.childTopics[index - 1];
				} else {
					this.currentTopic = this.topicDetail;
				}
				if (this.comments[index].length == 0) {
					//false 是为了解决从评论详情页面跳转到评论列表时，在切换tab时，某条评论一直为顶置状态
					this.getRecorderCommentList(index, 1, false);
				}
				this.currentComments = this.comments[index];

			},
			goBack() {
				console.log(this.fromMyTopiclist);
				if ("搜索页" == this.fromMyTopiclist || "我的记录" == this.fromMyTopiclist|| "我的收藏" == this.fromMyTopiclist) {
					uni.navigateBack({

					})
				} else {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}


			},
			//对应案例的接口
			getRecorderDetail(id) {
				uni.showLoading({
					title: 'loading'
				});
				//http://127.0.0.1:3000/topics/5e0ffbfe468ec052e0d91a4f?fields=childTopics
				var url = config.baseUrl + '/topics/' + id + '?fields=childTopics';
				uni.request({
					method: 'GET',
					url: url,
					timeout: 10000,
					success: (res) => {
						var statusCode = res.statusCode;
						if (200 == statusCode) {
							var v = {
								loadmoreText: '上拉加载更多',
								isLoadingMore: false,
								currentPage: 1
							};
							this.topicDetail = res.data;
							var topicIds = [this.topicDetail._id];
							console.log("bbbbbjinlial==" + JSON.stringify(this.topicDetail.childTopics));
							for (var i = 1; i < this.topicDetail.childTopics.length + 1; i++) {
								console.log("jinlial==" + this.topicDetail.childTopics.length);
								this.belowTabBars.push(i + 1);
								this.comments.push([]);
								this.loadmoreInfoes.push(v);
								topicIds.push(this.topicDetail.childTopics[i - 1]._id)
							}
							//如果从动态页进来的
							for (var i = 0; i < topicIds.length; i++) {
								if (topicIds[i] == this.currentTopicId) {
									this.belowTabIndex = i;
									this.tabIndex = 1;
								}
							}
							this.getRecorderCommentList(this.belowTabIndex, 1, true);
						} else {
							uni.stopPullDownRefresh();
						}
					},
					fail: (res) => {
						uni.stopPullDownRefresh();
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			//对应comment的接口
			getRecorderCommentList(index, page, flag) {
				if (index > 0) {
					this.currentTopic = this.topicDetail.childTopics[index - 1];

				} else {
					this.currentTopic = this.topicDetail
				}

				var topicId = this.currentTopic._id;
				var idFromNewsPage = this.commentIdFromNewsPage;


				var url = config.baseUrl + '/topics/' + topicId + '/comments?page=' + page;
				if (this.commentIdFromNewsPage && flag) {
					url = config.baseUrl + '/topics/' + topicId + '/comments?page=' + page + '&idFromNews=' + this.commentIdFromNewsPage;
				}
				uni.showLoading({
					title: 'loading'
				});
				uni.request({
					method: 'GET',
					url: url,
					success: (res) => {
						var statusCode = res.statusCode;
						if (200 == statusCode) {

							if (res.data.length > 0) {
								if (page === 1) {
									this.comments[index] = res.data;
								} else {
									this.comments[index] = this.comments[index].concat(res.data);
								}
								this.belowTabIndex = index;
								this.currentComments = this.comments[index];
							}
							if (res.data.length > 0) {
								this.loadmoreInfoes[index].loadmoreText = "上拉加载更多";
								this.loadmoreInfoes[index].currentPage = this.loadmoreInfoes[index].currentPage + 1;
							} else {
								this.loadmoreInfoes[index].loadmoreText = "没有更多数据";
							}
						} else {
							console.log('else');
						}
					},
					fail: (res) => {
						console.log('fail');
					},
					complete: () => {
						this.loadmoreInfoes[index].isLoadingMore = false;
						uni.stopPullDownRefresh();
						uni.hideLoading();
					}
				});

			},
			goDetail(item) {
				var commentId = item._id;

				var rootTopicId = this.topicDetail._id;
				var currentTopicId = this.currentTopic._id;
				var url = '../commentdetils/commentdetils?topicId=' + currentTopicId + '&commentId=' + commentId + '&rootTopicId=' +
					rootTopicId;
				console.log(url);
				uni.navigateTo({
					url
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.currentTopic.casePics
				})
			},
			addChildTopic() {
				var url = '../addrecorder/addrecorder?id=' +
					this.topicDetail._id +
					'&doctor=' + this.topicDetail.doctor +
					'&clinic=' + this.topicDetail.clinic +
					'&diseseName=' + this.topicDetail.diseseName +
					'&location=' + this.topicDetail.location;
				uni.navigateTo({
					url
				})
			},
			sentComment() {
				var newComment = this.newComment;

				var data = {
					content: newComment,
					rootTopicId: this.topicDetail._id
				}
				var token = uni.getStorageSync(config.token);
				var b = config.baseUrl + '/topics/' + this.currentTopic._id + '/comments';
				console.log('vvvvvvv++' + b);
				uni.request({
					method: 'POST',
					url: b, //仅为示例，并非真实接口地址。
					data: data,
					header: {
						'content-type': 'application/json', //自定义请求头信息
						'Authorization': 'Bearer ' + token //通过登录接口，生成新的token
					},
					success: (res) => {
						console.log('yyyyyyyyyyyyyyyyy');
						console.log(res);
						var statusCode = res.statusCode;
						console.log(statusCode);
						if (200 == statusCode) {
							this.newComment = '';
							this.comments[this.belowTabIndex].unshift(res.data);
							uni.showToast({
								title: "评论成功",
								duration: 3000
							});

						} else if (401 == statusCode) {
							//token 相关到错误
							//1,session过期或不存在：直接手机号和密码登录（后期短信验证码），返回token
							//2，session 有效：session登录(一键登录)，返回token
							//跳转后显示微信登录按钮。
							this.checkSession();

						} else {
							uni.showToast({
								title: "评论失败",
								duration: 2000,
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "评论失败"
						});
					}
				});

			},
			checkSession(){
				uni.checkSession({
					success: (e) => {
						var weixinsession = uni.getStorageSync(config.sessionkey);
						if (weixinsession.length > 0) {
							uni.navigateTo({
								url: '../loginnew/loginnew'
								
							})
						} else {
							uni.navigateTo({
								url: '../authorityRequst/authorityRequst'
							})
						}
				
					},
					fail: () => {
						console.log("yijinggoqdi")
						uni.navigateTo({
							url: '../authorityRequst/authorityRequst'
						})
					}
				});
			}

		}
	}
</script>

<style>
	.add-comment {
		width: 100%;
		border: #007AFF solid 1px;
		position: fixed;
		bottom: 0px;
	}

	.out-top-tab {
		display: flex;
		justify-content: center;
	}

	.uni-swiper-tab {
		border-bottom: 1upx solid #EEEEEE;
		display: flex;
		justify-content: center;
		line-height: 50upx;
		height: 60upx;
	}

	.swiper-tab-list {
		color: #969696;
		font-weight: bold;
		font-size: 25upx;
		width: 150upx;
	}

	.uni-swiper-tab .active {
		color: #343434;
	}

	.active .swiper-tab-line {
		border-bottom: 2upx solid #FEDE33;
		width: 70upx;
		margin: auto;
		border-top: 5upx solid #FEDE33;
		border-radius: 30upx;
	}

	.active .swiper-tab-line1 {
		background-color: #007AFF;
		border-radius: 15upx;
		color: #FFFFFF;
	}

	.below-swiper-tab-list {
		font-size: 30upx;
		width: 80upx;
		display: inline-block;
		text-align: center;
		color: #555;
	}

	.comment-list {
		padding-left: 30upx;
		display: flex;
		flex-direction: row;
	}

	.coomment-list-cell {
		display: flex;
		flex-direction: row;
		padding-top: 5upx;
	}

	/* detail */
	.out-input {
		padding-top: 30upx;
		padding-left: 70upx;
	}

	.radio {
		padding-left: 20upx;
	}

	.picker {
		display: flex;
		flex-flow: row;
	}

	.uni-list-cell {
		/* height: 100upx; */
		padding-left: 30upx;
	}

	.uni-form-item {
		/* height: 100upx; */
		display: block;
		/* height: 100upx; */
		padding-left: 30upx;
		padding-right: 30upx;
		width: auto;
		flex-direction: column;
	}

	.uni-list-cell::after {
		right: 30upx;
		transform: scaleY(1);
		background-color: #FFFFFF;

	}

	.under-line {
		width: auto;
		height: 1upx;
		background-color: #007AFF;
		margin-left: 30upx;
		margin-right: 30upx;
	}

	/* .title {
		width: 150upx;
		font-size: 30upx;
		font-weight: bold;
	} */
	.title {
		width: 25%;
		float: left;
		font-size: large;
		font-weight: bold;
	}

	.textarea{
		font-size: large;
		display: block;
		margin-left: 32%;
		width: 60%;
		padding: 15rpx 25rpx;
		background-color: #FFFFFF;
	}

	.lable-radio {
		padding-top: 10upx;
		padding-right: 30upx;
	}

	.comment-list {
		padding-left: 40upx;
		display: flex;
		flex-direction: row;
	}

	.coomment-list-cell {
		display: flex;
		flex-direction: row;
		padding-top: 5upx;
	}

	.button-save {
		display: flex;
		flex-direction: row;
	}

	.uni-uploader-title {
		font-weight: bold;
		padding-top: 20upx;
	}

	.input-error {
		border: 2upx solid #FF3333;
	}

	.uni-uploader__file {
		background-color: #8A6DE9;
		margin: 0upx;
		width: 210upx;
		/* height: 510upx; */
	}


	.uni-uploader__img {
		display: block;
		width: 210upx;
		/* height: 210upx; */
	}

	.topic-list {
		height: 910upx;
	}

	.swiper-box {
		position: relative;
		background-color: #F7F7F7;
	}

	.add-button {
		font-size: 50upx;
		font-weight: bold;
		color: #007AFF;
		position: absolute;
		top: 30upx;
		right: 30upx;
		z-index: 1;
	}

	.comment-out {
		display: table;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
	}

	.comment-text {

		display: table-cell;
		width: 80%;
		height: 100upx;
		font-size: 40upx;
		background-color: #F4F5F6;
	}

	.comment-send {
		text-align: center;
		vertical-align: middle;
		display: table-cell;
		font-size: 40upx;
		color: #FFFFFF;
		background-color: #F0AD4E;
	}

	.image-list {
		border: #F0AD4E solid 1px;
		margin-bottom: 2px;
		display: block;
		height: 200upx;
		width: 200upx;
	}

	.image-out {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.refresh-button {
		position: fixed;
		bottom: 200upx;
		right: 30upx;
		font-size: 60upx;
		/* font-weight: bold; */
		color: #007AFF;
	}

	.load-more {
		text-align: center;
		color: #AAAAAA;
		padding: 15upx;
	}

	.myactive {
		background-color: #AAAAAA;
	}

	.uni-comment-content {
		font-size: large;
	}

	.uni-comment-replay-btn {
		font-size: larger;
	}
	.uni-input{
		font-size: large;
	}
	.titleDegress{
		padding-left: 20upx;padding-right: 20upx; width: 30%;
		float: left;
		font-size: large;
		font-weight: bold;
	}
</style>
